<template>
	<view @click="getCode">
		<slot :tips="tips"></slot>
		<u-code ref="uCode" :endText="endText" :changeText="changeText" :seconds="second" @end="end" @start="start"
			@change="codeChange"></u-code>
	</view>
</template>

<script>
	import http from "@/common/js/http.js";
	export default {
		name: "SendCode",
		props: {
			second: {
				type: Number,
				default: 60
			},
			api: {
				type: String,
				default: "/user/getSmsCode"
			},
			params: {
				type: Object,
				default: _ => ({})
			},
			changeText: {
				type: String,
				default: "x秒"
			},
			endText: {
				type: String,
				default: "重新获取"
			},
			disabled: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				tips: '',
			};
		},
		methods: {
			getCode() {
				if (this.disabled) return;

				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					this.$k.showLoading('正在获取验证码');
					http.post(this.api, this.params).then(res => {
						uni.hideLoading();
						// 这里此提示会被this.start()方法中的提示覆盖
						this.$k.toast('验证码已发送');
						// 通知验证码组件内部开始倒计时
						this.$refs.uCode.start();
					}).catch(err => {
						this.$k.toast("验证码发送失败")
					});


				} else {
					this.$k.toast('倒计时结束后再发送');
				}
			},
			end() {
				this.$emit("end");
			},
			start() {
				this.$emit("start")
			},
			codeChange(text) {
				this.tips = text;
			},
		}
	}
</script>

<style lang="scss">

</style>